package com.hanxiaozhang.threadbase2ndedition.no4threadend;

import java.util.concurrent.TimeUnit;

/**
 * 〈一句话功能简述〉<br>
 * 〈使用Interrupt，停止线程〉
 *
 * @author hanxinghua
 * @create 2021/11/3
 * @since 1.0.0
 */
public class No4Interrupt {
    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(() -> {
            long startTime = System.currentTimeMillis();
            while (!Thread.interrupted()) {
                // sleep or wait
                if ((System.currentTimeMillis() - startTime) > 500) {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        System.out.println("Thread is interrupted");
                        System.out.println(Thread.currentThread().isInterrupted());
                        // catch异常后，会把interrupt标识设置为false，如果需要打断标志，需要重新设置
                        Thread.currentThread().interrupt();
                        // 出现异常也停止循环 Tips：这就是比volatile的好处
                        break;
                    }
                }
            }
            System.out.println("t1 end");
        });

        t.start();
        TimeUnit.SECONDS.sleep(1);
        t.interrupt();
    }

}
